<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
      crossorigin="anonymous"
    /> -->
    <style>
      .pagination {
        justify-content: flex-end;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="margin: 20px 0; display: flex">
          <input
            type="text"
            class="form-control search-input"
            style="width: 200px"
          />
          <button
            type="button"
            class="btn btn-primary search"
            style="margin: 0 20px"
          >
            搜索
          </button>
          <button type="button" class="btn btn-primary reset">重置</button>
        </div>

        <!-- Button trigger modal -->
        <button
          type="button"
          class="btn btn-primary"
          data-toggle="modal"
          data-target="#exampleModal"
        >
          新增
        </button>
      </div>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">姓名</th>
            <th scope="col">年龄</th>
            <th scope="col">性别</th>
            <th scope="col">住址</th>
            <th scope="col">手机号</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>

      <!-- 分页 -->
      <nav aria-label="Page navigation example">
        <ul class="pagination"></ul>
      </nav>

      <!-- Modal -->
      <div
        class="modal fade"
        id="exampleModal"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">新增学员</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form>
                <div class="form-group">
                  <label for="name">姓名</label>
                  <input type="text" class="form-control" id="name" />
                </div>
                <div class="form-group">
                  <label for="age">年龄</label>
                  <input type="number" class="form-control" id="age" />
                </div>
                <div class="form-group">
                  <label for="sex">性别</label>
                  <select class="form-control" id="sex">
                    <option disabled>请选择</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="address">住址</label>
                  <input type="text" class="form-control" id="address" />
                </div>
                <div class="form-group">
                  <label for="phone">手机号</label>
                  <input type="text" class="form-control" id="phone" />
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
              >
                取消
              </button>
              <button
                type="button"
                class="btn btn-primary confirm"
                data-dismiss="modal"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"
      crossorigin="anonymous"
    ></script> -->
    <script>
      // 定义接口前缀
      const baseUrl = "http://localhost:3000/students";
      // 每页条数
      let pageSize = 4;
      // 当前第几页
      let currentPage = 1;

      const ajax = (url, data = {}, method = "GET") => {
        return new Promise((resolve, reject) => {
          $.ajax({
            url: baseUrl + url,
            method,
            data: {
              ...data,
              token: localStorage.getItem("token"),
            },
            success(res) {
              resolve(res);
            },
          });
        });
      };

      const getListData = async (data) => {
        const res = await ajax("/list", {
          pageSize: pageSize,
          currentPage: currentPage,
          ...data,
        });
        if (res.status === 0) {
          // 拼接的是表格
          let str = "";
          res.result.forEach((item) => {
            str += `
              <tr>
                <th>${item.name}</th>
                <td>${item.age}</td>
                <td>${item.sex === 1 ? "男" : "女"}</td>
                <td>${item.address || "未知"}</td>
                <td>${item.phone || "未知"}</td>
                <td>
                  <button type="button" class="btn btn-warning">编辑</button>
                  <button type="button" class="btn btn-danger" onclick="removeItem('${
                    item._id
                  }')">删除</button>
                </td>
              </tr>
            `;
          });
          $("tbody").html(str);
          // 拼接分页
          let str2 =
            '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
          const num = Math.ceil(res.count / pageSize);
          for (let i = 1; i <= num; i++) {
            str2 += `<li class="page-item"><a class="page-link" href="#" onclick="paginationClick(${i})">${i}</a></li>`;
          }
          str2 +=
            '<li class="page-item"><a class="page-link" href="#">Next</a></li>';
          $(".pagination").html(str2);
        } else if (res.status === 999) {
          location.href = "./login.html";
        }
      };

      window.onload = () => {
        getListData();
      };

      // 点击搜索按钮
      $(".search").on("click", () => {
        // console.log($(".search-input").val());
        const value = $(".search-input").val();
        if (value) {
          currentPage = 1;
          getListData({
            name: $(".search-input").val(),
          });
        } else {
          getListData();
        }
      });

      // 点击重置按钮
      $(".reset").on("click", () => {
        $(".search-input").val("");
        getListData();
      });

      // 分页的点击
      const paginationClick = (i) => {
        currentPage = i;
        getListData();
      };

      // 删除事件
      const removeItem = async (id) => {
        const res = await ajax("/del", { id }, "POST");
        if (res.status === 0) {
          // 删除成功以后需要再次请求
          getListData();
          // 告诉用户删除成功了
          alert(res.msg);
        }
      };

      $(".confirm").on("click", async () => {
        // console.log({
        //   name: $("#name").val(),
        //   age: $("#age").val(),
        //   sex: $("#sex").val(),
        //   address: $("#address").val(),
        //   phone: $("#phone").val(),
        // });
        const res = await ajax(
          "/add",
          {
            name: $("#name").val(),
            age: $("#age").val(),
            sex: $("#sex").val(),
            address: $("#address").val(),
            phone: $("#phone").val(),
          },
          "POST"
        );
        if (res.status === 0) {
          getListData();
        }
      });
    </script>
  </body>
</html>
